/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.common.el;

import javax.el.ELContext;
import javax.el.ELResolver;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * {@link ELResolverDecorator} that blocks invocations using reflection or native calls.
 *  阻止使用反射或本机调用的装饰器
 */
public class ELResolverReflectionBlockerDecorator extends ELResolverDecorator {

    private static final String JAVA_REFLECTION_PACKAGE = "java.lang.reflect";
    private static final Predicate<Method> IS_FINAL = method -> Modifier.isFinal(method.getModifiers());
    private static final Predicate<Method> IS_NATIVE = method -> Modifier.isNative(method.getModifiers());
    private static final Set<String> NATIVE_METHODS = Arrays.stream(Object.class.getMethods())
            .filter(IS_FINAL.or(IS_NATIVE))
            .map(Method::getName)
            .collect(Collectors.toSet());

    public ELResolverReflectionBlockerDecorator(ELResolver resolver) {
        super(resolver);
    }

    @Override
    public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
        final String basePackageName = base.getClass().getPackage().getName();
        if (JAVA_REFLECTION_PACKAGE.equals(basePackageName)) {
            throw new IllegalArgumentException("Illegal use of Reflection in a JUEL Expression");
        }

        if (NATIVE_METHODS.contains(method)) {
            throw new IllegalArgumentException("Illegal use of Native Method in a JUEL Expression");
        }
        return super.invoke(context, base, method, paramTypes, params);
    }
}
